import plugin from '../../../lib/plugins/plugin.js'
import fetch from "node-fetch";
import { segment } from "oicq";
import common from "../../../lib/common/common.js";

export class bilibili extends plugin {
  constructor() {
    super({
      name: 'B站解析',
      dsc: 'B站解析',
      event: 'message',
      priority: 1,
      rule: [
        {
          reg: '^(.*)QQ小程序(.*)哔哩哔哩(.*)https:(.*)b23.tv(.*)|https://www.bilibili.com(.*)|https://b23.tv(.*)$',
          fnc: 'bzjx'
        },
      ]
    })
  }

  async bzjx(e) {
    //获取解析连接
    let Message = e.msg.indexOf('https');
    if (Message == 0) {
      var bvurl = e.msg;
    } else {
      Message = e.msg.indexOf('com.tencent.structmsg');
      if (Message == 8) {
        const CQjsondata = JSON.parse(e.msg);
        var bvurl = CQjsondata.meta.news.jumpUrl
      } else {
        Message = e.msg.indexOf('QQ小程序');
        if (Message == 29) {
          //处理信息 兼容一下无终端NTQQ机器人框架
          let botMessage = e.msg.indexOf('当前版本不支持该消息类型，请使用最新版本手机QQ查看')
          if (botMessage != -1) {
            var mag = e.msg.replace(/\s+/g, '').replace('当前版本不支持该消息类型，请使用最新版本手机QQ查看', '');
          } else {
            var mag = e.msg
          }
          const CQjsondata = JSON.parse(mag);
          var bvurl = CQjsondata.meta.detail_1.qqdocurl
        }
      }
    }
    let tv = bvurl.indexOf('tv/')
    let id = bvurl.substring(tv + 3, tv + 10)
    let url = 'https://b23.tv/' + id
    let res = await fetch(url)
    bvurl = res.url
    let jxapi = `https://api.xingzhige.com/API/b_parse/?url=${bvurl}`
    let jx = await fetch(jxapi)
    let api = await jx.json();
    if (api.msg == "video") {
      let title = `解析完成，点击查看`
      let title1 = `类型：视频`
      let imgmsg = segment.image(api.data.video.fm)
      let msg2 = `视频链接:https://www.bilibili.com/video/av${api.data.aid}\n--------------------------------\n标题:${api.data.video.title}\n\n简介:${api.data.video.desc}\n\n作者:${api.data.owner.name}\n--------------------------------\n点赞:${api.data.stat.like}    收藏:${api.data.stat.favorite}  \n投币:${api.data.stat.coin}      转发:${api.data.stat.share}`
      var message = [title]
      message.push(title1)
      message.push(`视频封面:`,imgmsg,msg2)
      message.push(segment.video(api.data.video.url))
      message.push(`视频下载链接:${api.data.video.url}`)
      e.reply(await common.makeForwardMsg(this.e, message))
      return true
    }
    if (api.msg == "cv") {
      let title = `解析完成，点击查看`
      let title1 = `类型：专栏`
      let msg2 = `专栏链接:${bvurl}\n--------------------------------\n作者:${api.data.user.name}\n\n点赞:${api.data.stast.like}    收藏:${api.data.stast.favorite}  \n投币:${api.data.stast.coin}      转发:${api.data.stast.share}`
      let msg3 = `内容：\n${api.data.essay}`
      var message = [title]
      message.push(title1)
      message.push(msg2)
      message.push(msg3)
      e.reply(await common.makeForwardMsg(this.e, message))
      return true
    }
  }
}
